/**
 * 将菜单列表转为菜单树
 * @param menuList 菜单列表
 * @returns 菜单树
 */
export function menuListToTree(menuList: API.Menu[]): API.MenuTreeNode[] {
  const menuListTemp = menuList.sort((a, b) => {
    if (typeof a.sort === 'number' && typeof b.sort === 'number') {
      return a.sort - b.sort;
    }
    return -1;
  });
  const pathMap = menuListTemp.reduce<Map<React.Key, API.MenuTreeNode>>((pathMap, item) => {
    if (item.id) {
      pathMap.set(item.id, item);
    }
    return pathMap;
  }, new Map());

  return menuListTemp.reduce<API.MenuTreeNode[]>((treeNodeList, item) => {
    if (item.parentId) {
      const parent = pathMap.get(item.parentId);
      if (parent) {
        if (parent.children) {
          parent.children.push(item);
        } else {
          parent.children = [item];
        }
        return treeNodeList;
      }
    }
    treeNodeList.push(item);
    return treeNodeList;
  }, []);
}

/**
 * 将后端菜单树格式化为符合前端的菜单树
 * @param menuTree 菜单树
 * @returns 符合 Antd Pro 的菜单树
 */
export function menuFormat(menuTree: API.MenuTreeNode[]): System.MenuTreeNode[] {
  return menuTree
    .filter((item) => item.visible === 0)
    .map<System.MenuTreeNode>((item) => {
      return {
        id: item.id,
        parentId: item.parentId,
        name: item.name,
        path: item.path,
        element: item.component,
        icon: item.icon,
        children: item.children && menuFormat(item.children),
      };
    });
}

export function pathInMenuTree(path: string, menuTree: System.MenuTreeNode[]): boolean {
  let res = false;
  for (let i = 0, limit = menuTree.length; i < limit; i++) {
    const { path: menuPath, children } = menuTree[i];
    if (path === menuPath || menuPath?.split('/').includes(path.replaceAll('/', ''))) {
      res = true;
      break;
    }
    if (children) {
      res = pathInMenuTree(path, children);
      if (res) {
        break;
      }
    }
  }
  return res;
}

export function findMenuPath(id: number, menuList: API.Menu[], base: string[] = []): string[] {
  let menu = menuList.find((item) => item.id === id);
  if (menu) {
    base.unshift(menu.path?.replaceAll('/', '') || '');
    if (typeof menu.parentId !== 'undefined') {
      findMenuPath(menu.parentId, menuList, base);
    }
  }
  return base;
}
